package com.nmcc.app_adherence;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class PersonsListingActivity extends Activity {
		private static ListView lstvwPersonsToEdit;
		private Spinner spnPersonsx;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_persons_listing);
		
		//addItemsOnSpinnerPersonToEdit();
		
		
		Button bpersons = (Button) findViewById(R.id.btnnew_person);
		bpersons.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   
        	   
        	   Go_To_Persons_Linker(arg0);
        	   //addItemsOnSpinnerPersonToEdit();
               
           }
        });  
        
		//btnEditSelectedPerson
		Button bpersonsedit = (Button) findViewById(R.id.btnEditSelectedPerson);
		bpersonsedit.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {

        	   EditSelectedPerson(arg0);
           }
        });  
		
		Button b55 = (Button) findViewById(R.id.btnFinishedHouseHoldGoToMonitoring);
        b55.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   //first take data to odk
        	   //ExportGPSDataToCSVTakeToODKDirect(arg0);
        	   GoToMonitoring();
           }
        });
		
		
    	Button b1980 = (Button) findViewById(R.id.btnDeleteSelectedPerson);
    	b1980.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   //first take data to odk

        	   ConfirmDeleteRecord(arg0);
        	   
           }
        });		
        		
	}

	@Override
	protected void onStart(){
		super.onStart();
		addItemsOnSpinnerPersonToEdit();
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.persons_listing, menu);
		return true;
	}

	public void addItemsOnSpinnerPersonToEdit() {
	//String[] args = {"tagname", "tagname", "tagname", "tagname", "tagname"};

		ListThePersonsInHouse();
  
    }	    
	
	public void Go_To_Persons_Linker(View view)
    {
		MySQLiteHelper db = new MySQLiteHelper(this);
		
		db.addSettingPersons("none");  
		
	   //'navigate to another screen'
	   final Context context = this;

       //give values
	   Intent intent = new Intent(context, Persons.class);
	   //intent.putExtra("cluster","22");
	    startActivity(intent);

    }
	
		
	public void ListThePersonsInHouse()
    {
	   	MySQLiteHelper mh = new MySQLiteHelper(this);
	   	MySQLiteHelper db1 = new MySQLiteHelper(this);
	   	
		SQLiteDatabase db = mh.getReadableDatabase();
		
		String hs_id = db1.GetSetting(3);

		//Toast.makeText(getApplicationContext(), hs_id, Toast.LENGTH_LONG).show();
		
		spnPersonsx = (Spinner) findViewById(R.id.spnPersons);
      List list = new ArrayList();
      	
      String haspersons="no";
		String name;
    	int age;
    	String relation;
    	int id;
		
    //}
 	
 		//now add the data, same order as above, check corresponding fields

 
		String valueToReturn="0";
	      String table = "Persons";
	         String[] columns = {"id","Name","Age","RelationshipToHHHeadLabel","household_id"};
	        // String where = "id=" + givenId + " and HouseID='" + givenhouseid + "'";//this is default so its acts as variable to be replaced
	      String where = "household_id='" + hs_id + "'";//this is default so its acts as variable to be replaced
	         
	         //String[] args = {"tagname", "tagname", "tagname", "tagname", "tagname"};
	         Cursor rs = db.query(table, columns, where, null, null, null, null);		

      if(rs.moveToFirst()){
           do{
        	   name= rs.getString(rs.getColumnIndex("Name"));
	        	relation= rs.getString(rs.getColumnIndex("RelationshipToHHHeadLabel"));
	        	age= rs.getInt(rs.getColumnIndex("Age"));
	        	id= rs.getInt(rs.getColumnIndex("id"));
    
	        	if (id>0){
  
	        		valueToReturn= name + ", " + age + ", " + relation + "          " + id;
	        		//String getpersondetails=GetPersonNameAndIDForListing(i, hs_id).toString();
      	     	  //String getpersondetails="fff";
      	  	     // list.add(gethousedetails);
      	 	    	 haspersons="yes";
      	 	    	 list.add(valueToReturn);
      	       }

             }while(rs.moveToNext());
         }
 	
				 	 if (haspersons.equals("yes"))
				        {
				      	  ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice, list);
				  	     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				      	  spnPersonsx.setAdapter(dataAdapter);
				      	  
				   	  }
 	 
       rs.close();
       db.close();

 	   //SendFileViaBluetoothFromSDCardFolder(view, "GPSData.csv");
 	}

	public void EditSelectedPerson(View view)
    {
		

	 	   MySQLiteHelper db = new MySQLiteHelper(this);
	
	        Spinner spnPersonsCC;
	        spnPersonsCC= (Spinner) findViewById(R.id.spnPersons);
	
	   	    String selectedpersonnum = getLast5CharactersOfChoicesAsValue(String.valueOf(spnPersonsCC.getSelectedItem()));
		 
	   	 String st=selectedpersonnum.trim();
	   	 
		//Toast.makeText(getApplicationContext(), st, Toast.LENGTH_LONG).show();
	   	 
		//String trimedHouseid = selectedHouseID.trim();
	   	 
	   	 
	   	 
		int num=Integer.parseInt(st);
		
	   	db.addSettingPersons(String.valueOf(num));   

		
	   //'navigate to another screen'
	   final Context context = this;

       //give values
	   Intent intent = new Intent(context, Persons.class);
	   //intent.putExtra("cluster","22");
	    startActivity(intent);

    }
 //}
	private String getLast5CharactersOfChoicesAsValue(String gnstr) {
		 //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
	       //String relat=String.valueOf(spnRelations1.getSelectedItem());
	       //check if its first option 'Select Gender.....  _00', then return null
	      
		 String lastcharacterUseForCompare = "0";
		 String Extractedlastcharacter = gnstr.substring(gnstr.length() - 1);
		 
		 if (lastcharacterUseForCompare==Extractedlastcharacter){
	    	   return null;
	      } else {
	    		   return gnstr.substring(gnstr.length() - 5);
	    		  
	       }
	    	   
	 } 
	public void GoToMonitoring(){
		 final Context context = this;
	     //give values
		   Intent intent = new Intent(context, PersonsListingActivity.class);
	     finish();

	     //final Context context2 = this;
	     //give values
		  // Intent intent = new Intent(context, Persons.class);
	     //finish();
	     
	     
	}
		
	
	public void DeleteSelectedPerson(View view)
    {
	        Spinner spnPersonsCC;
	        spnPersonsCC= (Spinner) findViewById(R.id.spnPersons);
	
	   	    String selectedpersonnum = getLast5CharactersOfChoicesAsValue(String.valueOf(spnPersonsCC.getSelectedItem()));
		 
	   	 String st=selectedpersonnum.trim();
   	 
		int num=Integer.parseInt(st);
		
		//selected person is num;
	   	MySQLiteHelper mh = new MySQLiteHelper(this);

		SQLiteDatabase db = mh.getWritableDatabase();

		int rowcount = db.delete("Persons", "id" + "=?", new String[]{ String.valueOf(num) });
      
		Log.d("No. of records deleted" , String.valueOf(rowcount));
		
		db.close();
		
		Toast.makeText(getApplicationContext(), "Person deleted.", Toast.LENGTH_LONG).show();
		
		int spinncount= spnPersonsCC.getAdapter().getCount();
		
		if (spinncount==1){
			final Context context = this;
		     //give values
			   Intent intent = new Intent(context, PersonsListingActivity.class);
		     finish();
			return;//close since if only one item it has errror
		}
		ListThePersonsInHouse();
		
 	}

	   public void ConfirmDeleteRecord(final View view){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Once deleted, this record will not be recovered. Are you sure you want to delete this record?")
			       .setCancelable(false)
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
			        	   
			        	   DeleteSelectedPerson(view);	   
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                // some code if you want
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();

			
		}
	
}
